package com.ideabove.heart;


import com.example.android.trivialdrivesample.util.IabHelper;
import com.example.android.trivialdrivesample.util.IabResult;
import com.example.android.trivialdrivesample.util.Inventory;
import com.example.android.trivialdrivesample.util.Purchase;
import com.ideabove.heart.custom.FreeCloset;
import com.ideabove.heart.custom.PayCloset;
import com.ideabove.heart.data.CallListAdapter;
import com.ideabove.heart.manager.AppManager;
import com.ideabove.heart.manager.MoeManager;
import com.ideabove.heart.manager.ScheduleManager;
import com.ideabove.heart.manager.SoundManager;
import com.ideabove.heart.util.LogUtil;
import com.ideabove.heart.util.MyUtil;
import com.ideabove.heart.util.MyUtil.ImageTouch;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class ShopActivity extends MyActivity{
	CallListAdapter adapter;
	ListView callList;
	SoundManager soundMgr;
	int SOUND_IDX = 1;

	int logoPress;
	FreeCloset focusedCloset;
	PayCloset paidCloset;
	IabResult paidResult;
	//com.ideabove.heart.item_test1

	// 구매루틴
	static final int RC_REQUEST = 10001;


	// The helper object
	IabHelper mHelper;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shop_closet);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		AppManager.start();
		
		// 효과음
		soundMgr = new SoundManager(this);
		soundMgr.addSound(SOUND_IDX, R.raw.button_press);

		
		// 인앱결제 초기화
		initPurchase();

		// 공짜 아이템 클릭
		LinearLayout free_layout = (LinearLayout) findViewById(R.id.closet_free);		
		for(int k = 0; k < free_layout.getChildCount(); k++){
			FreeCloset item = (FreeCloset)free_layout.getChildAt(k);
			item.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					freeClosetTouch((FreeCloset)v , event);	
					return true;
				}
			});
		}		

		// 유료아이템 클릭
		LinearLayout purchase_layout = (LinearLayout) findViewById(R.id.closet_purchase);		
		for(int k = 0; k < purchase_layout.getChildCount(); k++){
			PayCloset item = (PayCloset)purchase_layout.getChildAt(k);
			item.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					payClosetTouch((PayCloset)v , event);					
					return true;
				}
			});
		}
		
		// 확인
		ImageView btn_shop_confirm = (ImageView) findViewById(R.id.btn_shop_confirm);
		btn_shop_confirm.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				MyUtil.touchMe(v, event, new ImageTouch() {
					
					@Override
					public void touch(View v, MotionEvent event) {
						
						if(focusedCloset != null){
							ScheduleManager.setDefaultDress(ShopActivity.this, focusedCloset.dress, focusedCloset.hair );		
							
							MoeManager.setWhatWillIdo(MoeManager.DO_SHOP_CLOSET_AFTER); // 메인에서 모에를 호출함.
							Intent intent = new Intent(ShopActivity.this, MoeActivity.class);
							startActivity(intent);
							finish();
							
						}else{
							// 효과음
							soundMgr.playSound(SOUND_IDX);
							AlertDialog.Builder ab=new AlertDialog.Builder(ShopActivity.this); 
							ab.setMessage("의상을 선택해 주세요.");					
							ab.setPositiveButton("확인", null);
							ab.show();
						}
					}
				});
				return true;
			}
		});

		// 샾로고 10번 누르면 씨쓰룩이 완성된다.
		ImageView shop_logo = (ImageView) findViewById(R.id.shop_logo);
		shop_logo.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				logoPress = logoPress + 1;
				
				if(logoPress > 10){
					logoPress = 0;
					ScheduleManager.setDefaultDress(ShopActivity.this, "dress_seethrough.png", "hair_pajama.png" );
					MoeManager.setWhatWillIdo(MoeManager.DO_SHOP_CLOSET_AFTER); // 메인에서 모에를 호출함.
					Intent intent = new Intent(ShopActivity.this, MoeActivity.class);
					startActivity(intent);
					finish();
				}
			}
		});
		
	}

	// 인앱결제 초기화
	public void initPurchase(){

		String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlw/ZUFovvrmtfIess0UrgZNYh5WmWBFBYeZWU6mv3F0Q4JEpSyrn8ipuHOKSX80w6cjn+udz/gx7wuXwAJ+YLYiPt/Q1Uqabbt0Kyt3beZnqHx16jrLpZoXs4n97vulzgZJXPcgnsgZCVsmiAM8Nfw6w2o5GSpIGk5JdB2yzTXtRp2GvHFrOJaOJVw5XMf5G5g9qB2EPRtqKhndfhfbAAqW1J/8m7rGIeul0eXLHWMwCIWluFcbUxUbUcnb9Y9ethkidfC0gjaj+3IJtZ1tiyNM0jxoafzbhSsCR5MUw0UNl97pKWdV7Tn5xPPdhAVqx18JBhWz+otHygqlmO5F9JQIDAQAB";

		// Some sanity checks to see if the developer (that's you!) really followed the
		// instructions to run this sample (don't put these checks on your app!)
		if (base64EncodedPublicKey.contains("CONSTRUCT_YOUR")) {
			throw new RuntimeException("Please put your app's public key in MainActivity.java. See README.");
		}
		if (getPackageName().startsWith("com.example")) {
			throw new RuntimeException("Please change the sample's package name! See README.");
		}

		// Create the helper, passing it our context and the public key to verify signatures with
		LogUtil.e("Creating IAB helper.");
		mHelper = new IabHelper(this, base64EncodedPublicKey);

		// enable debug logging (for a production application, you should set this to false).
		mHelper.enableDebugLogging(true);

		// Start setup. This is asynchronous and the specified listener
		// will be called once setup completes.
		LogUtil.e("Starting setup.");
		mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
			public void onIabSetupFinished(IabResult result) {
				LogUtil.e("Setup finished.");

				if (!result.isSuccess()) {
					// Oh noes, there was a problem.
					//                    complain("Problem setting up in-app billing: " + result);
					return;
				}

				// Hooray, IAB is fully set up. Now, let's get an inventory of stuff we own.
				LogUtil.e("Setup successful. Querying inventory.");
				mHelper.queryInventoryAsync(mGotInventoryListener);           
			}
		});
	}



	IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
		public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
			if (result.isFailure()) {
				//                complain("Failed to query inventory: " + result);
				return;
			}


			LinearLayout purchase_layout = (LinearLayout) findViewById(R.id.closet_purchase);		
			for(int k = 0; k < purchase_layout.getChildCount(); k++){

				PayCloset item = (PayCloset)purchase_layout.getChildAt(k);

				Purchase premiumPurchase = inventory.getPurchase(item.cashId);
				boolean mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
				item.isPaid = mIsPremium;
				item.invalidate();
			}
		}
	};


	// Callback for when a purchase is finished
	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
			if (result.isFailure()) {
				paidResult = result;
				AlertDialog.Builder ab=new AlertDialog.Builder(ShopActivity.this); 
				ab.setMessage("아이템 구매에 실패했습니다.");					
				ab.setPositiveButton("확인", null);
				ab.show();				
	            return;
	        }else{
	        	paidResult = result;
	        	focusedCloset = paidCloset;
	        }
		}    
	};


	/** Verifies the developer payload of a purchase. */
	boolean verifyDeveloperPayload(Purchase p) {
		String payload = p.getDeveloperPayload();
		return true;
	}


	public void payClosetTouch(final PayCloset closet, MotionEvent event){

		if(event.getAction() == MotionEvent.ACTION_UP){
			closetTouch(closet, event);

			if(!closet.isPaid){
				AlertDialog.Builder ab=new AlertDialog.Builder(ShopActivity.this); 
				ab.setMessage(closet.title+"(0.99$) 의상을 구매하시겠습니까?");					
				ab.setPositiveButton("구입", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						// 구매하기
						paidCloset = closet;
						mHelper.launchPurchaseFlow(ShopActivity.this,
								closet.cashId, IabHelper.ITEM_TYPE_INAPP, 
								RC_REQUEST, mPurchaseFinishedListener, "");		
						
					}
				});
				ab.setNegativeButton("취소", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
				ab.show();
			}else{
				setFocusCloset(closet);
			}
		}
	}

	public void freeClosetTouch(FreeCloset closet, MotionEvent event){

		if(event.getAction() == MotionEvent.ACTION_UP){
			closetTouch(closet, event);
			
			if(closet.opdate >= closet.alarmCnt){
				AlertDialog.Builder ab=new AlertDialog.Builder(ShopActivity.this); 
				ab.setMessage("훗.. 아직 이런 옷을 입어달라고 하는 것은 실례겠지?");					
				ab.setPositiveButton("확인", null);
				ab.show();
			}else{
				setFocusCloset(closet);
			}
		}
	}
	
	public void setFocusPayCloset(PayCloset closet){
		
		closet.isPaid = true;		
		setFocusCloset(closet);
	}
	
	public void setFocusCloset(FreeCloset closet){
		focusedCloset = closet;
		closet.isFocus = true;		// 해당 박스에만 포커스
		
		LinearLayout free_layout = (LinearLayout) findViewById(R.id.closet_free);
		for(int k = 0; k < free_layout.getChildCount(); k++){
			FreeCloset item = (FreeCloset)free_layout.getChildAt(k);
			item.invalidate();
		}			
		
		LinearLayout purchase_layout = (LinearLayout) findViewById(R.id.closet_purchase);
		for(int k = 0; k < purchase_layout.getChildCount(); k++){
			FreeCloset item = (FreeCloset)purchase_layout.getChildAt(k);
			item.invalidate();
		}
	}


	// 옷설명을 보여주고 기본옷으로 세팅한다.
	public void closetTouch(FreeCloset closet, MotionEvent event){

		// 효과음
		soundMgr.playSound(SOUND_IDX);

		// 모든 포커스를 제거
		LinearLayout free_layout = (LinearLayout) findViewById(R.id.closet_free);		
		for(int k = 0; k < free_layout.getChildCount(); k++){
			FreeCloset item = (FreeCloset)free_layout.getChildAt(k);
			item.isFocus = false;
		}		
		LinearLayout purchase_layout = (LinearLayout) findViewById(R.id.closet_purchase);		
		for(int k = 0; k < purchase_layout.getChildCount(); k++){
			FreeCloset item = (FreeCloset)purchase_layout.getChildAt(k);
			item.isFocus = false;
		}		

		// 아래 상세 설명 표시
		ImageView charector_img = (ImageView) findViewById(R.id.charectr_detail_img);		
		charector_img.setImageResource(getResources().getIdentifier(closet.display, "drawable", getPackageName()));

		TextView charector_title = (TextView) findViewById(R.id.charectr_detail_title);		
		charector_title.setText(closet.title);

		TextView charector_desc = (TextView) findViewById(R.id.charectr_detail_desc);
		charector_desc.setText(closet.desc);
		
		// 유료리본
		if(closet instanceof PayCloset){
			ImageView charectr_detail_ribon = (ImageView) findViewById(R.id.charectr_detail_ribon);		
			charectr_detail_ribon.setVisibility(View.VISIBLE);
			ImageView charectr_free_ribon = (ImageView) findViewById(R.id.charectr_free_ribon);
			charectr_free_ribon.setVisibility(View.INVISIBLE);
			
		}else{ // 무료리본
			ImageView charectr_detail_ribon = (ImageView) findViewById(R.id.charectr_detail_ribon);		
			charectr_detail_ribon.setVisibility(View.INVISIBLE);
			
			ImageView charectr_free_ribon = (ImageView) findViewById(R.id.charectr_free_ribon);
			charectr_free_ribon.setVisibility(View.VISIBLE);
			
			if(closet.ribonBig != null){
				charectr_free_ribon.setImageResource(getResources().getIdentifier(closet.ribonBig, "drawable", getPackageName()));
			}
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			finish();			
//			AppManager.start();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// Pass on the activity result to the helper for handling
		if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
			// not handled, so handle it ourselves (here's where you'd
			// perform any handling of activity results not related to in-app
			// billing...
			super.onActivityResult(requestCode, resultCode, data);
		}
		else {
			
			if(!paidResult.isFailure()){
				setFocusPayCloset(paidCloset);
			}			
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AppManager.pause(ShopActivity.this);		
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(mHelper != null){
			mHelper.dispose();
		}
		mHelper = null;
	}
}
